using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace SymAutomate
{
    class AESEncryption
    {
        #region private variables
        private string _PassPhrase;
        private string _SaltValue;
        private string _HashAlgorithm;
        private int _PasswordIterations;
        private string _InitVector;
        private int _KeySize;
        #endregion


        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="_PassPhrase">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. We assume that this
        /// passphrase is an ASCII string.
        /// </param>
        /// <param name="_SaltValue">
        /// Salt value used along with passphrase to generate password. Salt can
        /// be any string. In this example we assume that salt is an ASCII string.
        /// </param>
        /// <param name="_HashAlgorithm">
        /// Hash algorithm used to generate password. Allowed values are: "MD5" and
        /// "SHA1". SHA1 hashes are a bit slower, but more secure than MD5 hashes.
        /// </param>
        /// <param name="_PasswordIterations">
        /// Number of iterations used to generate password. One or two iterations
        /// should be enough.
        /// </param>
        /// <param name="_InitVector">
        /// Initialization vector (or IV). This value is required to encrypt the
        /// first block of plaintext data. For RijndaelManaged class IV must be 
        /// exactly 16 ASCII characters long.
        /// </param>
        /// <param name="_KeySize">
        /// Size of encryption key in bits. Allowed values are: 128, 192, and 256. 
        /// </param>
        #region Constructor
        public AESEncryption(string _PassPhraseIn, string _SaltValueIn, string _HashAlgorithmIn, int _PasswordIterationsIn,
                             string _InitVectorIn, int _KeySizeIn)
        {
            _PassPhrase = _PassPhraseIn;
            _SaltValue = _SaltValueIn;
            _HashAlgorithm = _HashAlgorithmIn;
            _PasswordIterations = _PasswordIterationsIn;
            _InitVector = _InitVectorIn;
            _KeySize = _KeySizeIn;
        }
        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="_PassPhraseIn">
        /// Passphrase from which a pseudo-random password will be derived. The
        /// derived password will be used to generate the encryption key.
        /// Passphrase can be any string. In this example we assume that this
        /// passphrase is an ASCII string.
        /// </param>
        #region Constructor
        public AESEncryption(string _PassPhraseIn)
        {
            _PassPhrase = _PassPhraseIn;
            _SaltValue = "5wBZCm2NBORfK4bC60k4";
            _HashAlgorithm = "SHA1";
            _PasswordIterations = 2;
            _InitVector = "hamUJQOixyuv0M0g";
            _KeySize = 256;
        }
        #endregion

        /// <summary>
        /// Encrypts specified plaintext using Rijndael symmetric key algorithm and returns a base64-encoded result.
        /// </summary>
        /// <param name="_PlainText">
        /// Plaintext value to be encrypted.
        /// </param>
        /// <returns>
        /// Encrypted value formatted as a base64-encoded string.
        /// </returns>
        #region public string Encrypt(string _PlainText)
        public string Encrypt(string _PlainText)
        {
            // Convert strings into byte arrays.
            // Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8 
            // encoding.
            byte[] _InitVectorBytes = Encoding.ASCII.GetBytes(_InitVector);
            byte[] _SaltValueBytes = Encoding.ASCII.GetBytes(_SaltValue);

            // Convert our plaintext into a byte array.
            // Let us assume that plaintext contains UTF8-encoded characters.
            byte[] _PlainTextBytes = Encoding.UTF8.GetBytes(_PlainText);

            // First, we must create a password, from which the key will be derived.
            // This password will be generated from the specified passphrase and 
            // salt value. The password will be created using the specified hash 
            // algorithm. Password creation can be done in several iterations.
            PasswordDeriveBytes _Password = new PasswordDeriveBytes(
                                                            _PassPhrase,
                                                            _SaltValueBytes,
                                                            _HashAlgorithm,
                                                            _PasswordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] _KeyBytes = _Password.GetBytes(_KeySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged _SymmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            _SymmetricKey.Mode = CipherMode.CBC;

            // Generate _Encryptor from the existing key bytes and initialization 
            // vector. Key size will be defined based on the number of the key 
            // bytes.
            ICryptoTransform _Encryptor = _SymmetricKey.CreateEncryptor(
                                                             _KeyBytes,
                                                             _InitVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream _MemoryStream = new MemoryStream();

            // Define cryptographic stream (always use Write mode for encryption).
            CryptoStream _CryptoStream = new CryptoStream(_MemoryStream,
                                                         _Encryptor,
                                                         CryptoStreamMode.Write);
            // Start encrypting.
            _CryptoStream.Write(_PlainTextBytes, 0, _PlainTextBytes.Length);

            // Finish encrypting.
            _CryptoStream.FlushFinalBlock();

            // Convert our encrypted data from a memory stream into a byte array.
            byte[] _CipherTextBytes = _MemoryStream.ToArray();

            // Close both streams.
            _MemoryStream.Close();
            _CryptoStream.Close();

            // Convert encrypted data into a base64-encoded string.
            string _CipherText = Convert.ToBase64String(_CipherTextBytes);

            // Return encrypted string.
            return _CipherText;
        }
        #endregion

        /// <summary>
        /// Decrypts specified ciphertext using Rijndael symmetric key algorithm.
        /// </summary>
        /// <param name="_CipherText">
        /// Base64-formatted ciphertext value.
        /// </param>
        /// <returns>
        /// Decrypted string value.
        /// </returns>
        /// <remarks>
        /// Most of the logic in this function is similar to the Encrypt
        /// logic. In order for decryption to work, all parameters of this function
        /// - except _CipherText value - must match the corresponding parameters of
        /// the Encrypt function which was called to generate the
        /// ciphertext.
        /// </remarks>
        #region public string Decrypt(string ciperText)
        public string Decrypt(string _CipherText)
        {
            // Convert strings defining encryption key characteristics into byte
            // arrays. Let us assume that strings only contain ASCII codes.
            // If strings include Unicode characters, use Unicode, UTF7, or UTF8
            // encoding.
            byte[] _InitVectorBytes = Encoding.ASCII.GetBytes(_InitVector);
            byte[] _SaltValueBytes = Encoding.ASCII.GetBytes(_SaltValue);

            // Convert our ciphertext into a byte array.
            byte[] _CipherTextBytes = Convert.FromBase64String(_CipherText);

            // First, we must create a password, from which the key will be 
            // derived. This password will be generated from the specified 
            // passphrase and salt value. The password will be created using
            // the specified hash algorithm. Password creation can be done in
            // several iterations.
            PasswordDeriveBytes _Password = new PasswordDeriveBytes(
                                                            _PassPhrase,
                                                            _SaltValueBytes,
                                                            _HashAlgorithm,
                                                            _PasswordIterations);

            // Use the password to generate pseudo-random bytes for the encryption
            // key. Specify the size of the key in bytes (instead of bits).
            byte[] _KeyBytes = _Password.GetBytes(_KeySize / 8);

            // Create uninitialized Rijndael encryption object.
            RijndaelManaged _SymmetricKey = new RijndaelManaged();

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            _SymmetricKey.Mode = CipherMode.CBC;

            // Generate _Decryptor from the existing key bytes and initialization 
            // vector. Key size will be defined based on the number of the key 
            // bytes.
            ICryptoTransform _Decryptor = _SymmetricKey.CreateDecryptor(
                                                             _KeyBytes,
                                                             _InitVectorBytes);

            // Define memory stream which will be used to hold encrypted data.
            MemoryStream _MemoryStream = new MemoryStream(_CipherTextBytes);

            // Define cryptographic stream (always use Read mode for encryption).
            CryptoStream _CryptoStream = new CryptoStream(_MemoryStream,
                                                          _Decryptor,
                                                          CryptoStreamMode.Read);

            // Since at this point we don't know what the size of decrypted data
            // will be, allocate the buffer long enough to hold ciphertext;
            // plaintext is never longer than ciphertext.
            byte[] _PlainTextBytes = new byte[_CipherTextBytes.Length];

            // Start decrypting.
            int _DecryptedByteCount = _CryptoStream.Read(_PlainTextBytes,
                                                       0,
                                                       _PlainTextBytes.Length);

            // Close both streams.
            _MemoryStream.Close();
            _CryptoStream.Close();

            // Convert decrypted data into a string. 
            // Let us assume that the original plaintext string was UTF8-encoded.
            string _PlainText = Encoding.UTF8.GetString(_PlainTextBytes,
                                                       0,
                                                       _DecryptedByteCount);

            // Return decrypted string.   
            return _PlainText;
        }
        #endregion
    }
}
